package cn.lele.reggie.service.impl;

import cn.lele.reggie.common.R;
import cn.lele.reggie.dto.UserDto;
import cn.lele.reggie.entity.User;
import cn.lele.reggie.mapper.UserMapper;
import cn.lele.reggie.service.UserService;
import cn.lele.reggie.utils.ValidateCodeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public R<String> login(UserDto user, HttpServletRequest request) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getPhone,user.getPhone());
        User one = this.getOne(userLambdaQueryWrapper);
        if(one.getStatus() == 0){
            return R.error("账号已禁用");
        }
        String type=user.getType();
        if(type.equals("password")){
            if(!one.getPassword().equals(user.getPassword())){
                return R.error("密码不正确");
            }
        }else if(type.equals("checkcode")){
            log.info("验证前台用户验证码");
            String code = (String) redisTemplate.opsForValue().get("checkout_"+user.getPhone());
            if(code==null){
                return  R.error("请发送验证码");
            }
            if(!code.equals(user.getCode())){
                return R.error("验证码错误");
            }
            log.info("用户id--》"+one.getId()+"用户名："+one.getName());
            //删除验证码
            redisTemplate.delete("checkout_"+user.getPhone());
        }
        log.info("将userId加入到session");
        request.getSession().setAttribute("userId",one.getId());
        return R.success("登录成功");
    }

    @Override
    public R<String> sendMsg(User user) {
        String phone = user.getPhone();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User one = this.getOne(wrapper);
        if(one==null){
            log.info(user+"用户不存在，开始注册用户");
            user.setStatus(1);
            user.setPassword("123456");
            this.save(user);
        }
        //发验证码
        String msgCode = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("code--->"+msgCode);
        //将验证码保存到redis
        redisTemplate.opsForValue().set("checkout_"+phone,msgCode,5, TimeUnit.MINUTES);
        return R.success(msgCode);
    }
}
